<?php namespace App\Http\Controllers\Admin;

use App\Configs;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class SysController extends Controller {
    public function getWelcome()
    {
        return view('admin.sys.welcome');
    }

    public function getRepass()
    {
        return view('admin.sys.repass');
    }

    public function postRepass(Request $request)
    {
//        $validator = $this->validate($request, [
//            //'opwd' => 'required',
//            'password' => 'required|confirmed',
//        ]);

        $ret = ['state' => 'fail', 'message' => '未知错误，请刷新重试'];

        $validator = \Validator::make($request->all(), [
            'opwd' => 'required',
            'password' => 'required|confirmed|min:6|max:20',
        ], [], [
            'opwd' => '原密码',
            'password' => '新密码',
        ]);

        if ($validator->fails()) {
            $message = $validator->messages();
            if ($message->has('opwd')) {
                $ret['message'] = $message->first('opwd');
            } else {
                $ret['message'] = $message->first('password');
            }
        } else {
            if (\Auth::validate(['name' => \Auth::user()->name, 'password' => $request->input('opwd')])) {
                $user = \Auth::user();
                $user->password = bcrypt($request->input('password'));
                $user->save();
                $ret['state'] = 'success';
                $ret['message'] = '密码修改成功，下次登录请使用新密码';
            } else {
                $ret['message'] = '原密码错误';
            }
        }

        return \Response::json($ret);
    }

    public function getSetting()
    {
        $configs = \Config::get('setting.configs');
        $keys = $models = [];

        foreach($configs as $t => $c) {
            $keys = array_merge($keys, array_keys($c['options']));
        }

        foreach($keys as $key) {
            $models[$key] = Configs::val($key, 'model');
        }

        return view('admin.sys.setting', ['models' => $models, 'configs' => $configs]);
    }

    public function postSetting(Request $request)
    {
        $data = $request->all();
        foreach($data['Configs'] as $key => $config) {
            $model = Configs::firstOrNew(['key' => $key]);
            $model->val = $config['val'];
            $model->save();
        }

        return \Response::json(['state' => 'success', 'message' => '操作成功']);
    }

    public function getClearcache(){
        Cache::flush();
        return redirect()->guest('admin');
    }
}
